<script>
import {createProps} from '@/utils';

export default {
  name: 'FormManagerTabs',
  model: {
    prop: 'active',
    event: 'change'
  },
  props: {
    tabs: createProps(Array),
    active: createProps(String),
    beforeChange: createProps(Function)
  },
  render(h) {
    return h('div', {class: 'form-manager-tabs'}, this.createTabs(h));
  },
  methods: {
    createTabs(h) {
      let res = (this.tabs || []).map(tab => this.renderTab(tab, h));
      return this.insertDash(res, h);
    },
    insertDash(list, h) {
      let res = [list[0]];
      for (let i = 1; i < list.length; i++) {
        res.push(this.createDivider(h));
        res.push(list[i]);
      }
      return res;
    },
    createDivider(h) {
      return h('div', {class: 'form-manager-tab-divider'});
    },
    renderTab(tab, h) {
      return h('div', {
        class: ['form-manager-tab', {
          'form-manager-tab-active': tab.key === this.innerActive
        }],
        on: {
          click: () => this.change(tab.key),
        }
      }, this.createTitle(tab, h));
    },
    createTitle(tab, h) {
      return [
        h('div', {class: 'form-manager-tab-title-icon'}),
        h('span', {class: 'form-manager-tab-title'}, tab.title)
      ];
    },
    change(v) {
      let change = () => this.$emit('change', v);
      if(!this.active) {
        change();
      } else {
        if(this.active === v) {
          return;
        }
        if (this.beforeChange) {
          this.beforeChange(this.innerActive, change);
        } else {
          change();
        }
      }
    },
  },
  computed: {
    innerActive: {
      get() {
        if (!this.active) {
          let defaultKey = this.tabs[0].key;
          this.change(defaultKey);
          return defaultKey;
        }
        return this.active;
      },
      set(v) {
        this.change(v);
      }
    }
  }
};
</script>
<style>
.form-manager-tabs {
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  user-select: none;
}


.form-manager-tab:hover {
  color: #39adfb;
}

.form-manager-tab {
  height: 100%;
  display: flex;
  padding: 0 10px;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: white;
}


.form-manager-tab * {
  transition: all 200ms ease;
}

.form-manager-tab-title-icon {
  height: 12px;
  width: 12px;
  border-radius: 50%;
  border: 2px solid #c9c9c9;
  margin-right: 15px;
  margin-top: 2px;
}

.form-manager-tab:hover .form-manager-tab-title-icon {
  border: 2px solid #39adfb;
}

.form-manager-tab-divider {
  width: 80px;
  height: 0;
  border: 1px dashed #4a4a4a;
}


.form-manager-tab-active .form-manager-tab-title-icon {
  border: 2px solid #39adfb;
  background: #39adfb;
  box-shadow: 0 0 2px 2px #39adfb;
}

.form-manager-tab-active {
  color: #39adfb !important;
}
</style>